package com.cmes.mes.basic.core.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cmes.cache.service.CacheService;
import com.cmes.core.constant.enums.EnableStatus;
import com.cmes.jdbc.service.GenericService;
import com.cmes.mes.audit.constant.AuditStatusEnum;
import com.cmes.mes.basic.core.entity.VendorEntity;
import com.cmes.mes.basic.core.repository.VendorRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 供应商
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public class VendorService extends GenericService<VendorRepository, VendorEntity> {

    private static final String CACHE_KEY = "mes:vendor";
    private final CacheService cacheService;

    // region 缓存

    @SuppressWarnings("unused")
    @PostConstruct
    public void init() {
        cacheService.register(CACHE_KEY, "全部客户");
    }

    public List<VendorEntity> activeCustomer() {
        return cacheService.getCache(CACHE_KEY, () -> list(Wrappers.<VendorEntity>lambdaQuery()
                .eq(VendorEntity::getAuditStatus, AuditStatusEnum.AUDITED.getCode())
                .eq(VendorEntity::getStatus, EnableStatus.ENABLE.getCode())));
    }

    public void removeCache() {
        try {
            cacheService.removeCache(CACHE_KEY);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    // endregion

}
